package org.jeecg.modules.product.risk.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.product.risk.entity.TbBaseControlMeasures;
import org.jeecg.modules.product.risk.entity.TbBaseDangerInvestigation;
import org.jeecg.modules.product.risk.entity.TbBaseRiskEvents;
import org.jeecg.modules.product.risk.service.ITbBaseControlMeasuresService;
import org.jeecg.modules.product.risk.service.ITbBaseRiskEventsService;
import org.jeecg.modules.product.risk.vo.TbBaseRiskEventsPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 安全风险事件信息
 * @Author: jeecg-boot
 * @Date:   2024-03-02
 * @Version: V1.0
 */
@Tag(name="安全风险事件信息")
@RestController
@RequestMapping("/TbBaseRiskEvents/tbBaseRiskEvents")
@Slf4j
public class TbBaseRiskEventsController {
	@Autowired
	private ITbBaseRiskEventsService tbBaseRiskEventsService;
	@Autowired
	private ITbBaseControlMeasuresService tbBaseControlMeasuresService;
	
	/**
	 * 分页列表查询
	 *
	 * @param tbBaseRiskEvents
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "安全风险事件信息-分页列表查询")
	@Operation(summary="安全风险事件信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TbBaseRiskEvents>> queryPageList(TbBaseRiskEvents tbBaseRiskEvents,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		QueryWrapper<TbBaseRiskEvents> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskEvents, req.getParameterMap());
		Page<TbBaseRiskEvents> page = new Page<TbBaseRiskEvents>(pageNo, pageSize);
		IPage<TbBaseRiskEvents> pageList = tbBaseRiskEventsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tbBaseRiskEventsPage
	 * @return
	 */
	@AutoLog(value = "安全风险事件信息-添加")
	@Operation(summary="安全风险事件信息-添加")
    //@RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TbBaseRiskEventsPage tbBaseRiskEventsPage) {
		TbBaseRiskEvents tbBaseRiskEvents = new TbBaseRiskEvents();
		BeanUtils.copyProperties(tbBaseRiskEventsPage, tbBaseRiskEvents);
		tbBaseRiskEventsService.saveMain(tbBaseRiskEvents, tbBaseRiskEventsPage.getTbBaseControlMeasuresList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param tbBaseRiskEventsPage
	 * @return
	 */
	@AutoLog(value = "安全风险事件信息-编辑")
	@Operation(summary="安全风险事件信息-编辑")
    //@RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TbBaseRiskEventsPage tbBaseRiskEventsPage) {
		TbBaseRiskEvents tbBaseRiskEvents = new TbBaseRiskEvents();
		BeanUtils.copyProperties(tbBaseRiskEventsPage, tbBaseRiskEvents);
		TbBaseRiskEvents tbBaseRiskEventsEntity = tbBaseRiskEventsService.getById(tbBaseRiskEvents.getId());
		if(tbBaseRiskEventsEntity==null) {
			return Result.error("未找到对应数据");
		}
		tbBaseRiskEventsService.updateMain(tbBaseRiskEvents, tbBaseRiskEventsPage.getTbBaseControlMeasuresList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "安全风险事件信息-通过id删除")
	@Operation(summary="安全风险事件信息-通过id删除")
    @RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseRiskEventsService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "安全风险事件信息-批量删除")
	@Operation(summary="安全风险事件信息-批量删除")
    @RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseRiskEventsService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}


	 /**
	  *   通过id逻辑删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "安全风险事件信息-通过id逻辑删除")
	 @Operation(summary="安全风险事件信息-通过id逻辑删除")
	 @DeleteMapping(value = "/logicDelete")
	 public Result<?> logicDelete(@RequestParam(name="id",required=true) String id) {
		 TbBaseRiskEvents entity = tbBaseRiskEventsService.getById(id);
		 //禁止状态1是已删除，0是正常未删除
		 entity.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		 tbBaseRiskEventsService.updateById(entity);
		 return Result.OK("逻辑删除成功!");
	 }

	 /**
	  *  批量逻辑删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "安全风险事件信息-批量逻辑删除")
	 @Operation(summary="安全风险事件信息-批量逻辑删除")
	 @DeleteMapping(value = "/deleteLogicBatch")
	 public Result<?> deleteLogicBatch(@RequestParam(name="ids",required=true) String ids) {
		 List<TbBaseRiskEvents> list = tbBaseRiskEventsService.listByIds(Arrays.asList(ids.split(",")));
		 for (TbBaseRiskEvents entity : list) {
			 entity.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		 }
		 tbBaseRiskEventsService.updateBatchById(list);
		 return Result.OK("批量逻辑删除成功！");
	 }

	 /**
	  * 获取被逻辑删除
	  *
	  * @return
	  */
	 @GetMapping("/recycleBin")
	 public Result getRecycleBin() {
		 QueryWrapper<TbBaseRiskEvents> queryWrapper = new QueryWrapper<>();
		 //查询已经删除的数据
		 QueryWrapper<TbBaseRiskEvents> state = queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_1.toString());
		 List<TbBaseRiskEvents> list = tbBaseRiskEventsService.list(queryWrapper);
		 return Result.ok(list);
	 }

	 /**
	  * 还原被逻辑删除
	  *
	  * @param jsonObject
	  * @return
	  */
	 @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
	 public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		 String ids = jsonObject.getString("ids");
		 if (StringUtils.isNotBlank(ids)) {
			 List<TbBaseRiskEvents> list = tbBaseRiskEventsService.listByIds(Arrays.asList(ids.split(",")));
			 for (TbBaseRiskEvents entity : list) {
				 entity.setDeleted(CommonConstant.DEL_FLAG_0.toString());
			 }
			 tbBaseRiskEventsService.updateBatchById(list);
		 }
		 return Result.ok("还原成功");
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "安全风险事件信息-通过id查询")
	@Operation(summary="安全风险事件信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TbBaseRiskEvents> queryById(@RequestParam(name="id",required=true) String id) {
		TbBaseRiskEvents tbBaseRiskEvents = tbBaseRiskEventsService.getById(id);
		if(tbBaseRiskEvents==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbBaseRiskEvents);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "管控措施信息通过主表ID查询")
	@Operation(summary="管控措施信息主表ID查询")
	@GetMapping(value = "/queryTbBaseControlMeasuresByMainId")
	public Result<List<TbBaseControlMeasures>> queryTbBaseControlMeasuresListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TbBaseControlMeasures> tbBaseControlMeasuresList = tbBaseControlMeasuresService.selectByMainId(id);
		return Result.OK(tbBaseControlMeasuresList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbBaseRiskEvents
    */
    @RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbBaseRiskEvents tbBaseRiskEvents) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<TbBaseRiskEvents> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseRiskEvents, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<TbBaseRiskEvents> tbBaseRiskEventsList = tbBaseRiskEventsService.list(queryWrapper);

      // Step.3 组装pageList
      List<TbBaseRiskEventsPage> pageList = new ArrayList<TbBaseRiskEventsPage>();
      for (TbBaseRiskEvents main : tbBaseRiskEventsList) {
          TbBaseRiskEventsPage vo = new TbBaseRiskEventsPage();
          BeanUtils.copyProperties(main, vo);
          List<TbBaseControlMeasures> tbBaseControlMeasuresList = tbBaseControlMeasuresService.selectByMainId(main.getId());
          vo.setTbBaseControlMeasuresList(tbBaseControlMeasuresList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "安全风险事件信息列表");
      mv.addObject(NormalExcelConstants.CLASS, TbBaseRiskEventsPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("安全风险事件信息数据", "导出人:"+sysUser.getRealname(), "安全风险事件信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("TbBaseRiskEvents:tb_base_risk_events:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<TbBaseRiskEventsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseRiskEventsPage.class, params);
              for (TbBaseRiskEventsPage page : list) {
                  TbBaseRiskEvents po = new TbBaseRiskEvents();
                  BeanUtils.copyProperties(page, po);
                  tbBaseRiskEventsService.saveMain(po, page.getTbBaseControlMeasuresList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
